﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cfg;
using NHibernate;
using NHibernate.Context;
using NHibernate.Engine;

namespace FJASPX.Framwork.Dao
{
    public class NHSessionFactory
    {
        private static readonly object lockObj = new object();
        private static NHSessionFactory instance = null;
        public static ISessionFactory factory { get; set; }
        private NHSessionFactory() { }
        public static NHSessionFactory Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (lockObj)
                    {
                        if (instance == null)
                        {
                            instance = new NHSessionFactory();
                            Configuration cfg = new Configuration();
                            string connection = NHConnection.GetConfiguration();
                            factory = cfg.Configure(connection).BuildSessionFactory();
                        }
                    }
                }
                return instance;
            }
        }
        public ISession GetCurrentSession()
        {
            if (!CurrentSessionContext.HasBind(factory))
                CurrentSessionContext.Bind(factory.OpenSession());
            return factory.GetCurrentSession();
        }
        public ISession OpenSession()
        {
            return factory.OpenSession();
        }
        public static void DisposeCurrentSession()
        {
            ISession currentSession = CurrentSessionContext.Unbind(factory);
            currentSession.Close();
            currentSession.Dispose();
        }
    }
}
